import fetch from '../utils/fetch.js'
import C from '../constants'
import Cookie from 'react-cookie'




function sendRequest(payload){
    return {
        type:C.Actions.SEND_REQUEST,
        body:payload
    }
}

export function loggedIn(){
    return Cookie.load('token');
}

// 检测是否登录
// function checkLoginRequest(payload){
//     return {
//         type:C.Actions. CHECKLOGIN_REQUEST,
//         payload
//     }
// }
function checkLoginReceive(loginInfo){
    return {
        type:C.Actions. CHECKLOGIN_RECEIVE,
        loginInfo
    }
}
export function checkLogin(){
    return (dispatch, getState) => {
        dispatch(sendRequest({loading:true}))
        return fetch(C.Api.checkSSOLogin,{method:'POST'})
            .then(json => {
                dispatch(sendRequest({loading:false,loaded:true}))
                dispatch(checkLoginReceive(json))
            })
            .catch(err => {
                dispatch(sendRequest({loading:false,loaded:false}))
            })
    }
}


// 获取用户信息
export function receiveUserInfo(userinfo){
    return {
        type:C.Actions.RECEIVE_USERINFO,
        userinfo
    }
}
export function getUserInfo(){
    return (dispatch, getState) => {
        dispatch(sendRequest({loading:true}))
        return fetch(C.Api.getUserInfo,{method:'POST'})
            .then(json => {
                dispatch(sendRequest({loading:false,loaded:true}))
                dispatch(receiveUserInfo(json))
            })
            .catch(err => {
                dispatch(sendRequest({loading:false,loaded:false}))
            })
    }
}


// 登录
function loginSuccess(loginInfo){
    return {
        type:C.Actions.LOGIN_SUCCESS,
        loginInfo
    }
}
export function login(loginInfo){
    const credentials = {
        // str:encodeCredentials(loginInfo.userId,loginInfo.pwd)
    }
    return (dispatch, getState) => {
        dispatch(sendRequest({loading:true}))
        return fetch(`${API.ROOT_PATH}${API.LOGIN}`,{method:'POST',
            body:credentials
        })
        .then(json => {
            dispatch(sendRequest({loading:false,loaded:true}))
            dispatch(loginSuccess(json))
        })
        .catch(err => {
            dispatch(sendRequest({loading:false,loaded:false}))
        })
    }
}

// 判断
function receiveUserConfigureStatus(action){
    return {
        type:C.Actions.RECEIVE_USERCONFIGURESTATUS,
        body:action
    }
}
export function getUserConfigure(){
    return (dispatch, getState) => {
        console.log('getState:'+JSON.stringify(getState()));
        dispatch(sendRequest({loading:true}))
        return fetch(C.Api.userConfigureStatus,{method:'POST'})
        .then(json => {
            dispatch(sendRequest({loading:false,loaded:true}))
            dispatch(receiveUserConfigureStatus(json.body || json))
        })
        .catch(err => {
            dispatch(sendRequest({loading:false,loaded:false}))
        })
    }
}
